package fun.codedesign.principle.advice151.a040;

import fun.codedesign.principle.advice151.Notice;

enum Operation {
    ADD, SUB
}

/**
 * 匿名类的构造函数比较特殊 <br>
 * <pre>
 * </pre>
 *
 * @author zengjian
 * @create 2018-07-02 17:03
 * @since 1.0.0
 */
@Notice("这是一段比较费解的说明")
public class AnonymousSpecial {
    // 建议40：匿名类的构造函数很特殊，匿名内部类会调用对应的构造器，
    // 而不会像普通的继承构造一样，先调用无参然后调用自己的，
    public static void main(String[] args) {
        Caculator c = new Caculator(4, 3) {
            // 等价于先执行父类有参构造器(父类的无参代码块不会进行初始化)，然后执行以下构造代码块
            {
                setOperation(Operation.ADD);
            }
        };
        System.out.println(c.getResult()); // 没有出现无参构造器被调用的情况


        Caculator sub = new SubCaculator(4, 3); // 无参构造器被调用，并且返回的result为0
        sub.setOperation(Operation.ADD);
        System.out.println(sub.getResult());
    }
}

class Caculator {

    private int i, j, result;

    public Caculator() {
        System.out.println("---无参构造被调用---");
    }

    public Caculator(int i, int j) {
        this.i = i;
        this.j = j;
    }

    protected void setOperation(Operation operation) {
        result = operation.equals(Operation.ADD) ? i + j : i - j;
    }

    public int getResult() {
        return result;
    }
}

class SubCaculator extends Caculator {

    // 覆写父类构造方法，如果不调用super(i,j) 则默认调用无参构造器
    public SubCaculator(int i, int j) {
    }

    @Override
    protected void setOperation(Operation operation) {
        super.setOperation(Operation.ADD);
    }
}




